package org.pizza.did.autoconfigure;

import org.pizza.did.api.WorkerIdDistributor;
import org.pizza.did.properties.IdProperties;
import org.pizza.did.zookeeper.ZookeeperDistributor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author 高巍
 * @date 2020/10/13 3:40 下午
 */

@Configuration(
        proxyBeanMethods = false
)
@EnableConfigurationProperties({IdProperties.class})
public class ZookeeperDistributorConfiguration implements EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(ZookeeperDistributorConfiguration.class);
    private final IdProperties idProperties;
    private Environment environment;

    public ZookeeperDistributorConfiguration(IdProperties idProperties) {
        this.idProperties = idProperties;
    }

    @Bean
    @ConditionalOnMissingBean({WorkerIdDistributor.class})
    @ConditionalOnProperty(prefix = "did.zk", name = {"enabled"}, havingValue = "true", matchIfMissing = false)
    ZookeeperDistributor workerIdDistributor() {
        String ip = this.environment.getProperty("spring.cloud.client.ip-address");
        ZookeeperDistributor distributor = new ZookeeperDistributor(this.idProperties.getName(), ip, String.valueOf(this.idProperties.getZk().getPort()), this.idProperties.getZk().getAddress(), this.idProperties.getMaxWorkId());
        boolean init = distributor.init();
        if (!init) {
            log.error("IdGenerator ZookeeperDistributor  initialized  workId failed");
        }
        return distributor;
    }

    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}